package com.lexton.toolbox.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;

import com.lexton.toolbox.upload.Product;
import com.lexton.toolbox.upload.ProductReadUtil;
import com.lexton.util.excel.ExcelReadUtils;
import com.lexton.util.file.CopyFileUtil;
import com.lexton.util.file.DeleteFileUtil;
import com.lexton.util.file.ReadFileUtil;

public class MainWindow {
	private JFrame frame = null;
	private JTextField imagePath = null;
	private JTextField excelPath = null;
	private JTextField prefix = null;
	private JLabel imageLabel = null;
	private JLabel excelLabel = null;
	private JButton startBtn = null;
	private JCheckBox saveMode = null;
	private JButton imageBtn = null;
	private JButton excelBtn = null;
	private JMenuBar menuBar = null;
	private JTextField exportPath = null;
	private JPanel center = new JPanel();
	private JButton exportBtn;
	public MainWindow() {
		try {
			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated;
			org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();

			// 设置此开关量为false即表示关闭之，BeautyEye LNF中默认是true
			BeautyEyeLNFHelper.translucencyAtFrameInactive = false;
			// 设置属性即可：true表示使用ToolBar.background颜色实现纯
			// 色填充背景，BeautyEye中此属性默认是false
			//UIManager.put("ToolBar.isPaintPlainBackground", Boolean.FALSE);
			BeautyEyeLNFHelper.debug = true;

			// 自定义JToolBar ui的border
			/*Border bd = new org.jb2011.lnf.beautyeye.ch8_toolbar.BEToolBarUI.ToolBarBorder(
					UIManager.getColor("ToolBar.shadow") // Floatable时触点的颜色
					, UIManager.getColor("ToolBar.highlight")// Floatable时触点的阴影颜色
					, new Insets(6, 0, 11, 0)); // border的默认insets
			UIManager.put("ToolBar.border", new BorderUIResource(bd));*/
			// 是否显示设置按钮
			UIManager.put("RootPane.setupButtonVisible", false);
			//UIManager.put("TabbedPane.tabAreaInsets", new InsetsUIResource(0, 0, 0, 0));
			//UIManager.put("TabbedPane.contentBorderInsets", new InsetsUIResource(0, 0, 2, 0));
			//UIManager.put("TabbedPane.tabInsets", new InsetsUIResource(3, 10, 9, 10));

			Font frameTitleFont = (Font) UIManager.get("InternalFrame.titleFont");
			frameTitleFont = frameTitleFont.deriveFont(Font.PLAIN);
			UIManager.put("InternalFrame.titleFont", frameTitleFont);
			// UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
			frame = new JFrame("雷克斯登产品上传工具");
			
			frame.setIconImage(new ImageIcon(this.getClass().getResource("/icon/logo/logo128.png")).getImage());
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setMinimumSize(new Dimension(1000, 600));
			// 居中
			frame.setLocationRelativeTo(null);
			//frame.setForeground(Color.WHITE);

			// chooser = new JFileChooser();
			// chooser.setApproveButtonText("确定");
			// chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); //设置只选择

			menuBar = createMenus();
			frame.setJMenuBar(menuBar);
			
			prefix = new JTextField(10);
			
			excelLabel = new JLabel("产品导入表格：");
			excelPath = new JTextField(10);
			excelPath.setEnabled(false);
			excelBtn = new JButton("选择EXCEL文件");
			
			imageLabel = new JLabel("产品图片目录：");
			imagePath = new JTextField(10);
			imageBtn = new JButton("选择");
			
			exportBtn = new JButton("选择保存目录");
			
			saveMode = new JCheckBox("将图片分工作表保存");
			saveMode.setForeground(Color.red);
			
			startBtn = new JButton("开始处理");
			startBtn.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.blue));
			startBtn.setForeground(Color.white);
			
			imageBtn.addMouseListener(new MouseListener() {
				public void mouseClicked(MouseEvent arg0) {
					JFileChooser chooser = new JFileChooser();
					chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					chooser.showDialog(new JLabel(), "选择");
					File file = chooser.getSelectedFile();
					if (file != null && file.isDirectory()) {
						imagePath.setText(file.getAbsolutePath() + File.separator);
					}
				}

				public void mouseEntered(MouseEvent arg0) {}

				public void mouseExited(MouseEvent arg0) {}

				public void mousePressed(MouseEvent arg0) {}

				public void mouseReleased(MouseEvent arg0) {}
			});
			
			List<JCheckBox> checkBoxList = new ArrayList<JCheckBox>();
			
			excelBtn.addMouseListener(new MouseListener() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					JFileChooser jfc = new JFileChooser();
					jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
					jfc.showDialog(new JLabel(), "选择");
					File file = jfc.getSelectedFile();
					if (file != null && file.isFile()) {
						center.removeAll();
						
						checkBoxList.clear();
						excelPath.setText(file.getAbsolutePath());
						final Map<Integer, String> sheetInfo = ExcelReadUtils.readSheetInfo(excelPath.getText());
						center.add(new JLabel("选择需要导入的EXCEL的工作表："));
						sheetInfo.forEach((i, name)->{
							JCheckBox checkBox = new JCheckBox(name);
							center.add(checkBox);
							frame.pack();
							checkBoxList.add(checkBox);
						});
					}
				}

				public void mouseEntered(MouseEvent arg0) {}

				public void mouseExited(MouseEvent arg0) {}

				public void mousePressed(MouseEvent arg0) {}

				public void mouseReleased(MouseEvent arg0) {}
			});
			
			exportBtn.addMouseListener(new MouseListener() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					JFileChooser jfc = new JFileChooser();
					jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					jfc.showDialog(new JLabel(), "选择");
					File file = jfc.getSelectedFile();
					if (file != null && file.isDirectory()) {
						exportPath.setText(file.getAbsolutePath()+File.separator);
					}
				}

				@Override
				public void mouseEntered(MouseEvent arg0) {
				}

				@Override
				public void mouseExited(MouseEvent arg0) {
				}

				@Override
				public void mousePressed(MouseEvent arg0) {
				}

				@Override
				public void mouseReleased(MouseEvent arg0) {
				}
			});

			startBtn.addMouseListener(new MouseListener() {
				@Override
				public void mouseClicked(MouseEvent e) {
					try {
						startBtn.setEnabled(false);
						if (null == imagePath.getText() || "".equals(imagePath.getText())) {
							JOptionPane.showMessageDialog(null, "请选择产品图片目录!");
							return;
						}
						if (null == excelPath.getText() || "".equals(excelPath.getText())) {
							JOptionPane.showMessageDialog(null, "请选择产品导入EXCEL表!");
							return;
						}
						if (null == exportPath.getText() || "".equals(exportPath.getText())) {
							JOptionPane.showMessageDialog(null, "请选择保存目录!");
							startBtn.setEnabled(true);
							return;
						}
						
						DeleteFileUtil.deleteDirectory(imagePath.getText() + "上传图片/");
						DeleteFileUtil.deleteDirectory(imagePath.getText() + "上传图片-多角度/");
						List<Integer> sheets = new ArrayList<Integer>();
						for (int i=0; i<checkBoxList.size(); i++) {
							JCheckBox cb = checkBoxList.get(i);
							DeleteFileUtil.deleteDirectory(imagePath.getText() + "上传图片-多角度-"+cb.getText()+"/");
							if (cb.isSelected()) {
								sheets.add(i);
							}
						}
						
						if (sheets.size() == 0) {
							JOptionPane.showMessageDialog(null, "请选择需要导入的EXCEL工作表");
							return;
						}
						
						// 将图片目以及子目录的图片列出来，用于比较
						List<String> images = ReadFileUtil.readfile(imagePath.getText());

						// 解析EXCEL得到所有的产品SN
						List<Product> products = ProductReadUtil.readfile(excelPath.getText(), sheets);

						String imgPrefix = (prefix.getText()==null?"":prefix.getText());
						for (Product product : products) {
							for (String image : images) {
								if (image.toLowerCase().endsWith(product.getSn().replace(imgPrefix, "").toLowerCase() + ".png")) {
									product.setDesignPath(image);
								}

								if (image.toLowerCase().endsWith(product.getSn().replace(imgPrefix, "").toLowerCase() + ".jpg")) {
									product.setImagePath(image);
								}
								
								//判断图片的名称是不是（SN-数字）的格式，如果是则为多角度图
								String path = image.replace("\\", "/");
								String fileName = path.substring(path.lastIndexOf("/") + 1);
								fileName = fileName.substring(0, fileName.indexOf("."));
								
								if ((imgPrefix+fileName).startsWith(product.getSn()) && (imgPrefix+fileName).length()>product.getSn().length()+1) {
									String suffix = (imgPrefix+fileName).substring(product.getSn().length() + 1);
									Pattern pattern = Pattern.compile("[0-9]*"); 
									Matcher isNum = pattern.matcher(suffix);
									if (isNum.matches()) {
										if (image.toLowerCase().endsWith(".png")) {
											product.getImagesDesign().add(image);
										} else if (image.toLowerCase().endsWith(".jpg")) {
											product.getImagesProduct().add(image);
										}
									}
								}
							}
						}
						
						for (Product p : products) {
							String dir = "上传图片/";
							if (saveMode.isSelected()) {
								dir = "上传图片-" + p.getSheetName() + File.separator;
							}
							
							if (p.getDesignPath() != null && p.getImagePath() != null) {
								CopyFileUtil.copyFile(p.getDesignPath(), exportPath.getText() + dir + p.getSn() + ".png", true);
								CopyFileUtil.copyFile(p.getImagePath(), exportPath.getText() + dir + p.getSn() + ".jpg", true);
							}
							
							// 多角度图
							// 分类名称#产品编码#文件序号
							// 分类名称ProductImageType的BASIC、DESIGEN
							dir = "上传图片-多角度/";
							if (saveMode.isSelected()) {
								dir = "上传图片-多角度" + p.getSheetName() + File.separator;
							}
							
							if (p.getImagesProduct() != null) {
								for (String path : p.getImagesProduct()) {
									CopyFileUtil.copyFile(path, exportPath.getText() + dir + "BASIC#" + p.getSn() + "#" + UUID.randomUUID().toString().replaceAll("-", "") + "#YES.jpg", true);
								}
							}
							if (p.getImagesDesign() != null) {
								for (String path : p.getImagesDesign()) {
									CopyFileUtil.copyFile(path, exportPath.getText() + dir + "DESIGEN#" + p.getSn() + "#" + UUID.randomUUID().toString().replaceAll("-", "") + "#YES.png", true);
								}
							}
						}

						// 生产报表文件TXT，SN:XXXX 缺少产品图片，缺少设计图片
						File file = new File(exportPath.getText() + "/产品图片分析结果.txt");
						if (file.exists()) {
							file.delete();
						}

						FileOutputStream o = null;

						o = new FileOutputStream(file);
						for (Product p : products) {
							Boolean missImage = false;
							String content = "产品编号SN:" + p.getSn() + ",\t\t";
							if (p.getDesignPath() == null) {
								missImage = true;
								content += "缺少设计图片,\t\t";
							}

							if (p.getImagePath() == null) {
								missImage = true;
								content += "缺少产品图片,\t\t";
							}

							if (missImage) {
								o.write((content+"\n").getBytes("UTF-8"));
							}

						}
						o.close();
						JOptionPane.showMessageDialog(null, "处理完成!");
					} catch (Exception e2) {
						e2.printStackTrace();
						JOptionPane.showMessageDialog(null, e2.getMessage());
					} finally {
						startBtn.setEnabled(true);
					}
				}

				public void mousePressed(MouseEvent e) {}

				public void mouseReleased(MouseEvent e) {}

				public void mouseEntered(MouseEvent e) {}

				public void mouseExited(MouseEvent e) {}
			});
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 条件
		JPanel north = new JPanel();
		GridLayout northLayout = new GridLayout(4, 1);
		northLayout.setVgap(5);
		north.setBackground(Color.WHITE);
		north.setBorder(BorderFactory.createEmptyBorder(20,20,10,20));//设置内边距
		north.setLayout(northLayout);// 设置行列
		
		GridLayout northRowLayout = new GridLayout(1, 3);
		northRowLayout.setHgap(15);
		
		JPanel northRow01 = new JPanel();
		northRow01.setBackground(Color.WHITE);
		
		northRow01.setLayout(northRowLayout);
		northRow01.add(new JLabel("图片名称前缀："));
		northRow01.add(prefix);
		northRow01.add(new JLabel("自动拼接到导出图片名称前面(可不填)"));
		north.add(northRow01);
		
		JPanel northRow02 = new JPanel();
		northRow02.setBackground(Color.WHITE);
		northRow02.setLayout(northRowLayout);
		northRow02.add(imageLabel);
		northRow02.add(imagePath);
		northRow02.add(imageBtn);
		north.add(northRow02);
		
		JPanel northRow03 = new JPanel();
		northRow03.setBackground(Color.WHITE);
		northRow03.setLayout(northRowLayout);
		northRow03.add(excelLabel);
		northRow03.add(excelPath);
		northRow03.add(excelBtn);
		north.add(northRow03);
		
		JPanel northRow04 = new JPanel();
		northRow04.setBackground(Color.WHITE);
		northRow04.setLayout(northRowLayout);
		northRow04.setBounds(0, 0, 0, 0);
		northRow04.add(new JLabel("处理结果目录："));
		exportPath = new JTextField();
		exportPath.setEnabled(false);
		northRow04.add(exportPath);
		
		northRow04.add(exportBtn);
		north.add(northRow04);
		north.add(northRow04);
		
		frame.add(north, BorderLayout.NORTH);
		center.setLayout(new FlowLayout());
		center.setBackground(Color.WHITE);
		frame.add(center, BorderLayout.CENTER);
		
		JPanel south = new JPanel();
		south.setBackground(Color.WHITE);
		south.setLayout(new GridLayout(1, 2));
		south.setBorder(BorderFactory.createEmptyBorder(20,20,10,20));
		saveMode.setBackground(Color.WHITE);
		south.add(saveMode);
		south.add(startBtn);
		frame.add(south, BorderLayout.SOUTH);
		
		// 调置窗体背景全透明并完全隐藏一个窗体的标题栏
		// f.setUndecorated(true);
		// AWTUtilities.setWindowOpaque(f, false);
		// f.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
		frame.setVisible(true);
		// f.setBounds(300, 300, 1000, 600);
		frame.pack();
	}

	public JMenuBar createMenus() {
		// JMenuItem mi;
		// ***** create the menubar ****
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBackground(Color.WHITE);
		menuBar.getAccessibleContext().setAccessibleName("工具栏");

		// ***** create File menu
		JMenu fileMenu = (JMenu) menuBar.add(new JMenu("文件"));
		createMenuItem(fileMenu, "供应商产品EXCEL表格分析", "FileMenu.about_mnemonic", "新建文件", new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				new ParserWindow().setVisible(true);
			}
		});
//		createMenuItem(fileMenu, "保存", "FileMenu.about_mnemonic", "保存文件", null);
//		createMenuItem(fileMenu, "删除", "FileMenu.about_mnemonic", "删除文件", null);
//		createMenuItem(fileMenu, "另存为...", "FileMenu.about_mnemonic", "另存为...", null);
//		fileMenu.addSeparator();
//		JMenu editMenu = (JMenu) menuBar.add(new JMenu("编辑"));
//		createMenuItem(editMenu, "字体大小", "FileMenu.about_mnemonic", "字体大小", null);
//		createMenuItem(editMenu, "颜色", "FileMenu.about_mnemonic", "颜色", null);
//		createMenuItem(editMenu, "格式", "FileMenu.about_mnemonic", "格式", null);
//		fileMenu.addSeparator();
//		editMenu.addSeparator();
		return menuBar;
	}
	
	

	public JMenuItem createMenuItem(JMenu menu, String label, String mnemonic, String accessibleDescription,
			ActionListener actionListener) {
		JMenuItem mi = (JMenuItem) menu.add(new JMenuItem(label));

		// mi.setBorder(BorderFactory.createEmptyBorder());
		mi.setMnemonic(mnemonic.charAt(0));
		mi.getAccessibleContext().setAccessibleDescription(accessibleDescription);
		mi.addActionListener(actionListener);
		if (actionListener == null) {
			mi.setEnabled(false);
		}
		return mi;
	}
	
	public static void main(String[] args) {
		//多角度图
		String image ="G:\\Java_Source\\navigation_tigra_menu\\demo1\\img\\lev1_arrow.gif ";
		
		String fileName = image.substring(image.lastIndexOf("\\") + 1);
		
		System.out.println(fileName);
	}
}
